﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using BSF.SystemConfig;

namespace BSF.Tool
{
    public class PostAndGetHelper
    {
        // Methods
        #region 发送请求
        #region  向Url发送post请求
        /// <summary>
        /// 向Url发送post请求
        /// </summary>
        /// <param name="postData">发送数据</param>
        /// <param name="uriStr">接受数据的Url</param>
        /// <returns>返回网站响应请求的回复</returns>
        public static string RequestPost(string postData, string uriStr)
        {
            HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(uriStr);

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(postData);
            requestScore.Method = "Post";
            requestScore.ContentType = "application/x-www-form-urlencoded";
            requestScore.ContentLength = data.Length;
            requestScore.KeepAlive = true;

            Stream stream = requestScore.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();

            HttpWebResponse responseSorce;
            try
            {
                responseSorce = (HttpWebResponse)requestScore.GetResponse();
            }
            catch (WebException ex)
            {
                responseSorce = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
            }
            StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();

            requestScore.Abort();
            responseSorce.Close();
            responseSorce.Close();
            reader.Dispose();
            stream.Dispose();
            return content;
        }
        #endregion
        #region 得到程序post过来的数据
        /// <summary>
        /// 得到程序post过来的数据
        /// </summary>
        /// <returns></returns>
        private string GetPostContent()
        {
            string postStr = string.Empty;
            //Stream inputStream = Request.InputStream;
            //int contentLength = Request.ContentLength;
            //int offset = 0;
            //if (contentLength > 0)
            //{
            //    byte[] buffer = new byte[contentLength];
            //    for (int i = inputStream.Read(buffer, offset, contentLength - offset); i > 0; i = inputStream.Read(buffer, offset, contentLength - offset))
            //    {
            //        offset += i;
            //    }
            //    UTF8Encoding encoding = new UTF8Encoding();
            //    postStr = encoding.GetString(buffer);
            //}
            return postStr;
        }
        #endregion
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="strRequst"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public string SendRequest(string url, string strRequst, string method)
        {
            if (method == "POST")
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(strRequst);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                HttpWebResponse myResponse;
                try
                {
                    myResponse = (HttpWebResponse)myRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    myResponse = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
                }
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);//java编码格式
                //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
                string result = reader.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)myResponse.StatusCode;
                reader.Close();
                return result;
            }
            else if (method == "GET")
            {
                if (string.IsNullOrEmpty(url))
                    return "false";
                HttpWebRequest httpRequest;
                if (string.IsNullOrEmpty(strRequst))
                    httpRequest = (HttpWebRequest)WebRequest.Create(url);
                else if (!string.IsNullOrEmpty(strRequst) && url.IndexOf("?") > 0)
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "&" + strRequst);
                else
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                //HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                //HttpRequest.Timeout = 2000;
                httpRequest.Method = "GET";
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
                string result = sr.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)httpResponse.StatusCode;
                sr.Close();
                return result;//失败：[{filename:'96f5affa-5195-4272-973b-e71c27008430.jpg',ret:-1,msg:'nofile'}]，成功：[{filename:'96f5affa-5195-4272-973b-e71c27008430.jpg',ret:0}]
            }
            return "";
        }
        public static string SendRequest(string url, string strRequst, string method, Encoding encode)
        {
            if (method == "POST")
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(strRequst);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                HttpWebResponse myResponse;
                try
                {
                    myResponse = (HttpWebResponse)myRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    myResponse = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
                }
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), encode);
                string result = reader.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)myResponse.StatusCode;
                reader.Close();
                return result;
            }
            else if (method == "GET")
            {
                if (string.IsNullOrEmpty(url))
                    return "false";
                HttpWebRequest httpRequest;
                if (string.IsNullOrEmpty(strRequst))
                    httpRequest = (HttpWebRequest)WebRequest.Create(url);
                else if (!string.IsNullOrEmpty(strRequst) && url.IndexOf("?") > 0)
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "&" + strRequst);
                else
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                //HttpRequest.Timeout = 2000;
                httpRequest.Method = "GET";
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), encode);
                string result = sr.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)httpResponse.StatusCode;
                sr.Close();
                return result;
            }
            return "";
        }
        public static string SendRequest(string url, string strRequst, string method, WebProxy proxy)
        {
            if (method == "POST")
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(strRequst);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                HttpWebResponse myResponse;
                try
                {
                    myResponse = (HttpWebResponse)myRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    myResponse = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
                }
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);//java编码格式
                //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
                string result = reader.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)myResponse.StatusCode;
                reader.Close();
                return result;
            }
            else if (method == "GET")
            {
                if (string.IsNullOrEmpty(url))
                    return "false";
                HttpWebRequest httpRequest;
                if (string.IsNullOrEmpty(strRequst))
                    httpRequest = (HttpWebRequest)WebRequest.Create(url);
                else if (!string.IsNullOrEmpty(strRequst) && url.IndexOf("?") > 0)
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "&" + strRequst);
                else
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                //HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                httpRequest.Proxy = proxy;
                httpRequest.Timeout = 2000;
                httpRequest.Method = "GET";
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
                string result = sr.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)httpResponse.StatusCode;
                sr.Close();
                httpResponse.Close();
                return result;//失败：[{filename:'96f5affa-5195-4272-973b-e71c27008430.jpg',ret:-1,msg:'nofile'}]，成功：[{filename:'96f5affa-5195-4272-973b-e71c27008430.jpg',ret:0}]
            }
            return "";
        }
        #endregion

        #region 模拟请求
        /// <summary>
        /// 获取指定地址的html
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="PostData"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string GetHTML(string URL, string RequestMode, string PostData, System.Text.Encoding encoding)
        {
            bool isKeepAlive = false;
            string _Html = "";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";

            //if (_Cookies.Count > 0)
            //{
            //    request.CookieContainer.Add(new Uri(URL), _Cookies);
            //}
            //else
            //{
            //    request.CookieContainer = this.cookieContainer;
            //}

            //提交的数据
            if (PostData != null && PostData.Length > 0)
            {
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = RequestMode;

                byte[] b = encoding.GetBytes(PostData);
                request.ContentLength = b.Length;
                using (System.IO.Stream sw = request.GetRequestStream())
                {
                    try
                    {
                        sw.Write(b, 0, b.Length);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Post Data Error!!", ex);
                    }
                    finally
                    {
                        if (sw != null) { sw.Close(); }
                    }
                }
            }

            HttpWebResponse response = null;
            System.IO.StreamReader sr = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                //_Cookies = response.Cookies;
                sr = new System.IO.StreamReader(response.GetResponseStream(), encoding);
                _Html = sr.ReadToEnd();
            }
            catch (WebException webex)
            {
                if (webex.Status == WebExceptionStatus.KeepAliveFailure)
                {
                    isKeepAlive = true;
                }
                else
                {
                    throw new Exception("DownLoad Data Error", webex);
                }
            }
            catch (System.Exception ex)
            {
                throw new Exception("DownLoad Data Error", ex);
            }
            finally
            {
                if (sr != null) { sr.Close(); }
                if (response != null) { response.Close(); }
                response = null;
                request = null;
            }
            return _Html;
        }
        /// <summary>
        /// C#模拟http 发送post或get请求
        /// 向指定URL发送POST请求
        /// </summary>
        /// <param name="Url">URL地址</param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr)
        {
            String sResult = "";
            if (Url == "" || postDataStr == "")
            {
                return sResult;
            }
            try
            {
                //准备发送请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentType = "application/json; encoding=utf-8";
                request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(postDataStr);//计算对指定的 System.String 中的字符进行编码时所产生的字节数//request.ContentLength = postDataStr.Length;
                //request.CookieContainer = cookie;
                System.IO.Stream myRequestStream = request.GetRequestStream();
                //发送数据
                Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");//ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] bufferdata = encoding.GetBytes(postDataStr);//编码，尤其是汉字，事先要看下抓取网页的编码方式
                myRequestStream.Write(bufferdata, 0, bufferdata.Length);
                myRequestStream.Close();
                //异常：1.写入流的字节超出指定的 Content-Length 字节大小。2.请求被中止: 请求已被取消。原因是添加了 contentLength，注释掉request.ContentLength = data.Length;就好了
                //StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
                //myStreamWriter.Write(postDataStr);
                //myStreamWriter.Close();
                //获取返回数据
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //response.Cookies = cookie.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312"));
                sResult = myStreamReader.ReadToEnd();
                sResult.Trim();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            catch (Exception ex)
            {
                sResult = ex.Message;
                return sResult;
            }
            return sResult;
        }
        /// <summary>
        /// C#模拟http 发送post或get请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.Timeout = 20 * 1000;
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();

            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        /// <summary>
        /// C#模拟http 发送post或get请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpGetImg(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.Timeout = 20 * 1000;
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();

            //转byte[]然后在转成image 有异常
            //byte[] arrbyte = ConvertHelper.converter.StreamToBytes(myResponseStream);
            //string retString = ConvertHelper.converter.CreateImageFromBytes(arrbyte, @"c:\a.jpg");
            //ConvertHelper.converter.StreamToFile(myResponseStream, @"c:\b.jpg");
            #region 保存图片
            string retString = string.Empty;
            //Stream _stream = ConvertHelper.converter.getYCStream("http://himg2.huanqiu.com/attachment/081104/55c7e57181.jpg");
            //根目录路径，相对路径
            String rootPath = BSFConfig.QRImage + DirectoryHelper.CreateFilePath() + "/";
            String dirPath = System.Web.HttpContext.Current.Server.MapPath(rootPath);
            string filename = DirectoryHelper.CreateFileName() + ".jpg";
            DirectoryHelper.CreateDirectory(dirPath);

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("dirpath", dirPath);
            dict.Add("filename", filename);
            dict.Add("relativepath", rootPath + filename);
            FileHelper.SaveYCStream(myResponseStream, dict);
            retString = dict["relativepath"].ToString();
            #endregion

            //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            //retString = myStreamReader.ReadToEnd();
            //myStreamReader.Close();
            //myResponseStream.Close();
            return retString;
        }
        #endregion

        #region Http
        //Loogn.WeiXinSDK Util.cs
        public static Stream HttpPost(string action, byte[] data)
        {
            HttpWebRequest myRequest;
            myRequest = WebRequest.Create(action) as HttpWebRequest;
            myRequest.Method = "POST";
            myRequest.Timeout = 20 * 1000;
            myRequest.ContentType = "application/x-www-form-urlencoded";
            //myRequest.ContentType = "application/json; encoding=utf-8";
            myRequest.ContentLength = data.Length;
            using (Stream newStream = myRequest.GetRequestStream())
            {
                newStream.Write(data, 0, data.Length);
            }
            HttpWebResponse myResponse = myRequest.GetResponse() as HttpWebResponse;
            return myResponse.GetResponseStream();
        }
        public static string HttpPost2(string action, string data)
        {
            Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");//ASCIIEncoding encoding = new ASCIIEncoding();
            var buffer = encoding.GetBytes(data);
            //var buffer = Encoding.UTF8.GetBytes(data);
            using (var stream = HttpPost(action, buffer))
            {
                StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                data = sr.ReadToEnd();
                data.Trim();
                sr.Close();
                stream.Close();
                return data;
            }
        }
        public static string HttpPost2(string action, byte[] data)
        {
            using (var stream = HttpPost(action, data))
            {
                StreamReader sr = new StreamReader(stream);
                return sr.ReadToEnd();
            }
        }

        /// <summary>
        /// 上传多媒体文件
        /// </summary>
        /// <param name="action"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string HttpUpload(string action, string file)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest myRequest = WebRequest.Create(action) as HttpWebRequest;
            myRequest.Method = "POST";
            myRequest.ContentType = "multipart/form-data;boundary=" + boundary;
            StringBuilder sb = new StringBuilder();
            sb.Append("--" + boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"media\"; filename=\"" + file + "\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: application/octet-stream");
            sb.Append("\r\n\r\n");
            string head = sb.ToString();
            long length = 0;
            byte[] form_data = Encoding.UTF8.GetBytes(head);
            byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
            length = form_data.Length + foot_data.Length;

            using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                length += fileStream.Length;
                myRequest.ContentLength = length;
                Stream requestStream = myRequest.GetRequestStream();
                requestStream.Write(form_data, 0, form_data.Length);

                byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    requestStream.Write(buffer, 0, bytesRead);
                requestStream.Write(foot_data, 0, foot_data.Length);
            }
            HttpWebResponse myResponse = myRequest.GetResponse() as HttpWebResponse;
            StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string json = sr.ReadToEnd().Trim();
            sr.Close();
            if (myResponse != null)
            {
                myResponse.Close();
                myRequest = null;
            }
            if (myRequest != null)
            {
                myRequest = null;
            }

            //string json = string.Empty;
            //WebClient wx_upload = new WebClient();
            //string filename = file;//string filename =FileUpload1.PostedFile.FileName;//在IE浏览器里可以取到物理路径，但是在别的浏览器中无法获取物理路径
            //string extension = System.IO.Path.GetExtension(filename).ToLower();
            ////if (extension == ".jpg")
            ////{
            //    byte[] result = wx_upload.UploadFile(new Uri(action), filename);
            //    string resultjson = Encoding.Default.GetString(result);//在这里获取json数据，以获取media_id
            //    json = resultjson;
            ////}
            return json;
        }

        public static Tuple<Stream, string, string> HttpGet(string action)
        {
            HttpWebRequest myRequest = WebRequest.Create(action) as HttpWebRequest;
            myRequest.Method = "GET";
            myRequest.Timeout = 20 * 1000;
            HttpWebResponse myResponse = myRequest.GetResponse() as HttpWebResponse;
            var stream = myResponse.GetResponseStream();
            var ct = myResponse.ContentType;
            if (ct.IndexOf("json") >= 0 || ct.IndexOf("text") >= 0)
            {
                using (StreamReader sr = new StreamReader(stream))
                {
                    var json = sr.ReadToEnd();
                    return new Tuple<Stream, string, string>(null, ct, json);
                }
            }
            else
            {
                Stream MyStream = new MemoryStream();
                byte[] buffer = new Byte[4096];
                int bytesRead = 0;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                    MyStream.Write(buffer, 0, bytesRead);
                MyStream.Position = 0;
                return new Tuple<Stream, string, string>(MyStream, ct, string.Empty);
            }
        }

        public static string HttpGet2(string action)
        {
            return HttpGet(action).Item3;
        }

        #endregion

        #region KaixinHelper学习笔记 http://blog.csdn.net/yzh8734/article/details/4265485
        /// <summary>  
        /// 延迟毫秒数(默认为2秒)
        /// </summary>  
        protected int defer = 2000;
        /// <summary>  
        /// 与请求相关的cookie（用于保持session）  
        /// </summary>  
        protected CookieContainer cookies = new CookieContainer();
        /// <summary>  
        /// 关联Cookie，用于保持session会话  
        /// </summary>  
        public CookieContainer Cookies
        {
            get { return this.cookies; }
            set { this.cookies = value; }
        }
        /// <summary>  
        /// 发送Post类型请求  
        /// </summary>  
        /// <param name="url">请求地址</param>  
        /// <param name="postData">参数</param>  
        /// <returns></returns>  
        public WebResponse doPost(string url, string postData)
        {
            try
            {
                System.GC.Collect();
                System.Threading.Thread.Sleep(this.defer);
                byte[] paramByte = Encoding.UTF8.GetBytes(postData);        //转化  
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.Referer = "http://www.kaixin001.com/app/app.php?aid=1040";
                webRequest.Accept = "application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-silverlight, */*";
                webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)";
                webRequest.ContentLength = paramByte.Length;
                webRequest.CookieContainer = this.cookies;

                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(paramByte, 0, paramByte.Length);      //写入参数  
                newStream.Close();
                return webRequest.GetResponse();
            }
            catch (Exception ce)
            {
                throw ce;
            }
        }

        /// <summary>  
        /// 发送Get类型请求  
        /// </summary>  
        /// <param name="url">请求地址</param>  
        /// <returns></returns>  
        public WebResponse doGet(string url)
        {
            try
            {
                System.GC.Collect();
                //刷新太快开心网有验证  
                System.Threading.Thread.Sleep(this.defer);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.CookieContainer = this.cookies;
                webRequest.Method = "Get";
                return webRequest.GetResponse();
            }
            catch (Exception ce)
            {
                throw ce;
            }
        }

        /// <summary>  
        /// 根据相应返回字符串  
        /// </summary>  
        /// <param name="response"></param>  
        /// <returns></returns>  
        protected string ResponseToString(WebResponse response)
        {
            try
            {
                System.GC.Collect();
                StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string code = stream.ReadToEnd();
                stream.Close();
                response.Close();
                return code;
            }
            catch (Exception ce)
            {
                throw ce;
            }
        }
        #endregion

        #region task
        public bool doRequest(string url, byte[] postdata, ref string ResponseText)
        {
            HttpClient client = new HttpClient();
            Task<HttpResponseMessage> resultTask;
            try
            {
                HttpContent content = new ByteArrayContent(postdata, 0, postdata.Length);
                resultTask = client.PostAsync(url, content);
                resultTask.Wait();

                if ((int)resultTask.Result.StatusCode != 200)
                {
                    return false;
                }
                else
                {
                    #region C#使用Task创建任务
                    ////.NET 4 中 包含了新名称空间System.Threading.Task。它包含的类抽象出了线程的功能。使用Task类创建的任务是后台线程，所以在前台线程全部终止的时候，如果任务还没有全部执行万，就会被被动终止。
                    ////启动任务
                    ////怎样启动一个任务？代码中我们首先要添加using System.Threading.Tasks;引用。我们可以使用TaskFactory类或Task类的构造函数和Start()方法。在启动任务时，会创建Task类的一个实例。
                    ////使用TaskFactory创建一个任务
                    //TaskFactory tf = new TaskFactory();
                    //Task t1 = tf.StartNew(NewTask);
                    ////使用Task类de Factory创建一个任务
                    //Task t2 = Task.Factory.StartNew(NewTask);
                    /////////////////////////////////////////
                    //Task t3 = new Task(NewTask);
                    //t3.Start();
                    //Task t4 = new Task(NewTask, TaskCreationOptions.PreferFairness);
                    //t4.Start();
                    //System.Threading.Thread.Sleep(1000);//因为任务是后台线程，所以我们这里阻塞主线程一秒钟来等待任务全部执行完成
                    ////创建任务
                    //Task task = new Task(() =>
                    //{
                    //    //Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
                    //    for (int i = 0; i < 10; i++)
                    //    {
                    //        Console.WriteLine(i);
                    //    }
                    //});
                    ////创建连续的任务
                    ////通过创建任务，我们可以指定在一个任务完成过后，开始运行另外一个指定的任务。任务处理程序不带参数或者带一个Object类型的参数。连续处理程序有一个Task类型的参数，可以访问起始任务的相关信息。
                    ////连续的任务通过在任务上调用ContinueWith()方法来定义。t1.ContinueWith(SecondTask)方法表示，调用SecondTask()方法的新任务应该在t1任务完成后立即启动过，在第一个任务结束时，还可以启动多个任务。无论前一个任务是如何结束的，前面的连续任务总是在前面一个任务结束时启动，使用TaskContinueOptions枚举中的值可以指定连续任务只有在起始任务成功或者失败时启动，TaskContinueOptions的枚举值有...
                    //Task t1 = new Task(FirstTask, TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent);
                    //t1.Start();
                    //t1.Wait(); // need to wait for finishing.
                    ////Task<int> t2 = t1.ContinueWith<int>(SecondTask, TaskContinuationOptions.None);  
                    #endregion
                    Task<string> strTask = resultTask.Result.Content.ReadAsStringAsync();
                    //默认情况下，Task任务是由线程池线程异步执行。要知道Task任务的是否完成，可以通过task.IsCompleted属性获得，也可以使用task.Wait来等待Task完成。
                    strTask.Wait();
                    ResponseText = strTask.Result;
                    return true;
                }
            }
            catch (Exception ex)
            {
                ResponseText = ex.Message;
                return false;
            }
            finally
            {
                client.Dispose();
            }
        }
        private static void NewTask()
        {
            Console.WriteLine("开始一个任务");
            Console.WriteLine("Task id:{0}", Task.CurrentId);
            Console.WriteLine("任务执行完成");
        }
        static void FirstTask()
        {
            Console.WriteLine("第一个任务开始：TaskID:{0}", Task.CurrentId);
            System.Threading.Thread.Sleep(3000);
        }
        private static void SecondTask(Task task)
        {
            Console.WriteLine("任务{0}完成", task.Id);
            Console.WriteLine("第二个任务开始：TaskID:{0}", Task.CurrentId);
            Console.WriteLine("清理工作......");
            System.Threading.Thread.Sleep(3000);
        }
        /// <summary>
        /// 创建父子任务和任务工厂的使用
        /// 通过Task类创建的任务是顶级任务，可以通过使用 TaskCreationOptions.AttachedToParent 标识把这些任务与创建他的任务相关联，所有子任务全部完成以后父任务才会结束操作。
        /// </summary>
        public static void ParentChildTask()
        {
            Task<string[]> parent = new Task<string[]>(state =>
            {
                Console.WriteLine(state);
                string[] result = new string[2];
                //创建并启动子任务
                new Task(() => { result[0] = "我是子任务1。"; }, TaskCreationOptions.AttachedToParent).Start();
                new Task(() => { result[1] = "我是子任务2。"; }, TaskCreationOptions.AttachedToParent).Start();
                return result;
            }, "我是父任务，并在我的处理过程中创建多个子任务，所有子任务完成以后我才会结束执行。");
            //任务处理完成后执行的操作
            parent.ContinueWith(t =>
            {
                Array.ForEach(t.Result, r => Console.WriteLine(r));
            });
            //启动父任务
            parent.Start();
            Console.Read();
        }
        /// <summary>
        /// 创建任务工厂
        /// 如果需要创建一组具有相同状态的任务时，可以使用TaskFactory类或TaskFactory<TResult>类。这两个类创建一组任务时可以指定任务的CancellationToken、TaskCreationOptions、TaskContinuationOptions和TaskScheduler默认值。
        /// </summary>
        public static void TaskFactoryApply()
        {
            Task parent = new Task(() =>
            {
                System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();
                //创建任务工厂
                TaskFactory tf = new TaskFactory(cts.Token, TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
                //添加一组具有相同状态的子任务
                Task[] task = new Task[]{
                      tf.StartNew(() => { Console.WriteLine("我是任务工厂里的第一个任务。"); }),
                      tf.StartNew(() => { Console.WriteLine("我是任务工厂里的第二个任务。"); }),
                      tf.StartNew(() => { Console.WriteLine("我是任务工厂里的第三个任务。"); })
                  };
            });
            parent.Start();
            Console.Read();
        }
        #endregion

        #region URL解析
        public Dictionary<string, object> RequestCollection(List<object> list)
        {
            Dictionary<string, object> dicret = new Dictionary<string, object>();
            foreach (var _req in list)
            {
                //Newtonsoft.Json.Linq.JObject jo = Newtonsoft.Json.Linq.JObject.FromObject(_req.param);
                //string s = jo.ToString();
                //s = s.Replace("\\u0026", "&");
                //string requrl = string.Format("http://{0}/{1}/{2}", _req.serverurl, _req.controller, _req.method);
                //var ret = string.Empty;
                //bool r = doRequest(requrl, System.Text.Encoding.GetEncoding("GBK").GetBytes(s), ref ret);
                //dicret.Add(_req.cachekey, ret);

                string pageURL = "http://www.google.com.hk/search?hl=zh-CN&source=hp&q=%E5%8D%9A%E6%B1%87%E6%95%B0%E7%A0%81&aq=f&aqi=g2&aql=&oq=&gs_rfai=";
                Uri uri = new Uri(pageURL);
                string controllerAndmethod = uri.AbsolutePath;
                string[] results = controllerAndmethod.Split(new[] { '/' });
                string queryString = uri.Query;
                System.Collections.Specialized.NameValueCollection col = GetQueryString(queryString);
                string searchKey = col["q"];
                //结果 searchKey =  "博汇数码"
                //显示索引, 键,值
                for (int i = 0; i < col.Count; i++)
                    Console.WriteLine("[{0}]{1,-10}{2}", i, col.GetKey(i), col.Get(i));
                //显示键，值
                foreach (String s in col.AllKeys)
                    Console.WriteLine("{0,-10}{1}", s, col[s]);
                //NameValueCollection遍历
                foreach (string key in col.Keys)
                    Console.WriteLine("{0}:{1}", key, col[key]);
            }
            return dicret;
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static System.Collections.Specialized.NameValueCollection GetQueryString(string queryString)
        {
            return GetQueryString(queryString, null, true);
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="encoding"></param>
        /// <param name="isEncoded"></param>
        /// <returns></returns>
        public static System.Collections.Specialized.NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
        {
            queryString = queryString.Replace("?", "");
            System.Collections.Specialized.NameValueCollection result = new System.Collections.Specialized.NameValueCollection(StringComparer.OrdinalIgnoreCase);
            if (!string.IsNullOrEmpty(queryString))
            {
                int count = queryString.Length;
                for (int i = 0; i < count; i++)
                {
                    int startIndex = i;
                    int index = -1;
                    while (i < count)
                    {
                        char item = queryString[i];
                        if (item == '=')
                        {
                            if (index < 0)
                            {
                                index = i;
                            }
                        }
                        else if (item == '&')
                        {
                            break;
                        }
                        i++;
                    }
                    string key = null;
                    string value = null;
                    if (index >= 0)
                    {
                        key = queryString.Substring(startIndex, index - startIndex);
                        value = queryString.Substring(index + 1, (i - index) - 1);
                    }
                    else
                    {
                        key = queryString.Substring(startIndex, i - startIndex);
                    }
                    if (isEncoded)
                    {
                        result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
                    }
                    else
                    {
                        result[key] = value;
                    }
                    if ((i == (count - 1)) && (queryString[i] == '&'))
                    {
                        result[key] = string.Empty;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 解码URL.
        /// </summary>
        /// <param name="encoding">null为自动选择编码</param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MyUrlDeCode(string str, Encoding encoding)
        {
            if (encoding == null)
            {
                Encoding utf8 = Encoding.UTF8;
                //首先用utf-8进行解码                     
                string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
                //将已经解码的字符再次进行编码.
                string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
                if (str == encode)
                    encoding = Encoding.UTF8;
                else
                    encoding = Encoding.GetEncoding("gb2312");
            }
            return HttpUtility.UrlDecode(str, encoding);
        }

        /// <summary>
        /// 分析 url 字符串中的参数信息
        /// </summary>
        /// <param name="url">输入的 URL</param>
        /// <param name="baseUrl">输出 URL 的基础部分</param>
        /// <param name="nvc">输出分析后得到的 (参数名,参数值) 的集合</param>
        public static void ParseUrl(string url, out string baseUrl, out System.Collections.Specialized.NameValueCollection nvc)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            nvc = new System.Collections.Specialized.NameValueCollection();
            baseUrl = "";

            if (url == "")
                return;

            int questionMarkIndex = url.IndexOf('?');

            if (questionMarkIndex == -1)
            {
                baseUrl = url;
                return;
            }
            baseUrl = url.Substring(0, questionMarkIndex);
            if (questionMarkIndex == url.Length - 1)
                return;
            string ps = url.Substring(questionMarkIndex + 1);

            // 开始分析参数对    
            Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", RegexOptions.Compiled);
            MatchCollection mc = re.Matches(ps);

            foreach (Match m in mc)
            {
                nvc.Add(m.Result("$2").ToLower(), m.Result("$3"));
            }
        }
        #endregion

        public static byte[] GetResponseBytes(string apiUrl, string postData, string encoding)
        {
            byte[] bytes;
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(apiUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;
            request.Timeout = 0x4e20;
            System.Net.HttpWebResponse response = null;
            Encoding encoding2 = Encoding.UTF8;
            if (!string.IsNullOrEmpty(encoding))
            {
                encoding2 = Encoding.GetEncoding(encoding);
            }
            try
            {
                System.IO.StreamWriter writer = new System.IO.StreamWriter(request.GetRequestStream());
                writer.Write(postData);
                try
                {
                    if (writer != null)
                    {
                        writer.Close();
                    }
                }
                catch
                {
                }
                response = (System.Net.HttpWebResponse)request.GetResponse();
                using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding2))
                {
                    bytes = encoding2.GetBytes(reader.ReadToEnd());
                }
            }
            catch
            {
                bytes = encoding2.GetBytes("对不起，Url地址无法访问！");
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            return bytes;
        }

        public static string PostWebRequest(string postUrl, string paramData, string encoding)
        {
            string str = string.Empty;
            try
            {
                Encoding encoding2 = Encoding.UTF8;
                if (!string.IsNullOrEmpty(encoding))
                {
                    encoding2 = Encoding.GetEncoding(encoding);
                }
                byte[] bytes = encoding2.GetBytes(paramData);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                request.Method = "POST";
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                str = reader.ReadToEnd();
                reader.Close();
                response.Close();
                requestStream.Close();
            }
            catch (Exception)
            {
            }
            return str;
        }

        public static string RemoveJsonNull(string json)
        {
            json = Regex.Replace(json, ",\"\\w*\":null", string.Empty);
            json = Regex.Replace(json, "\"\\w*\":null,", string.Empty);
            json = Regex.Replace(json, "\"\\w*\":null", string.Empty);
            json = Regex.Replace(json, ",\"\\w*\":0", string.Empty);
            json = Regex.Replace(json, "\"\\w*\":0,", string.Empty);
            return json;
        }

        public static string RemoveUnsafeHtml(string content)
        {
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }
    }
}
